<!-- 学生时间安排列表页面 -->
<template>
    <div class="student-schedule">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>我的课程安排</span>
                    <div>
                        <el-button type="primary" @click="showCreateDialog">创建课程安排</el-button>
                    </div>
                </div>
            </template>

            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="已确认课程" name="confirmed">
                    <el-table :data="schedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="teacherName" label="教师姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="状态">
                            <template #default="scope">
                                <el-tag :type="getStatusType(scope.row.status)">
                                    {{ getStatusText(scope.row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button 
                                    v-if="scope.row.status === 1"
                                    type="success" 
                                    size="small" 
                                    @click="showFeedbackDialog(scope.row)"
                                >
                                    评价
                                </el-button>
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                                <el-button 
                                    v-if="(scope.row.status === 1 || scope.row.status === 2) && !scope.row.isPaid"
                                    type="warning"
                                    size="small"
                                    @click="goToPayment(scope.row)"
                                >
                                    支付
                                </el-button>
                                <el-button 
                                    v-if="scope.row.status === 2 || scope.row.status === 3"
                                    type="danger" 
                                    size="small" 
                                    @click="deleteSchedule(scope.row.id)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="待确认课程" name="pending">
                    <div v-if="pendingLoading" class="loading-container">
                        <el-skeleton :rows="5" animated />
                    </div>

                    <div v-else-if="pendingSchedules.length === 0" class="empty-data-tip">
                        <el-empty description="暂无待确认的课程安排" />
                    </div>
                    
                    <el-table v-else :data="pendingSchedules" style="width: 100%">
                        <el-table-column prop="tutoringTitle" label="课程名称" />
                        <el-table-column prop="teacherName" label="教师姓名" />
                        <el-table-column label="上课时间">
                            <template #default="scope">
                                {{ formatDateTime(scope.row.startTime) }} - {{ formatDateTime(scope.row.endTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="location" label="上课地点" />
                        <el-table-column prop="requirements" label="具体要求" show-overflow-tooltip />
                        <el-table-column label="创建者">
                            <template #default="scope">
                                {{ scope.row.createdBy === 'TEACHER' ? '教师创建的' : '我创建的' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <!-- 如果是教师创建的课程，学生可以确认和取消 -->
                                <template v-if="scope.row.createdBy === 'TEACHER'">
                                    <el-button 
                                        type="success" 
                                        size="small" 
                                        @click="handleConfirm(scope.row)"
                                    >
                                        确认
                                    </el-button>
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="handleCancel(scope.row)"
                                    >
                                        取消
                                    </el-button>
                                </template>
                                <!-- 如果是学生自己创建的课程，学生只能取消 -->
                                <template v-else>
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="handleCancel(scope.row)"
                                    >
                                        取消
                                    </el-button>
                                </template>
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="showPendingDetail(scope.row)"
                                >
                                    详情
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 创建课程安排对话框 -->
        <el-dialog v-model="createDialogVisible" title="创建课程安排" width="500px">
            <div v-if="availableTeachers.length === 0" class="empty-data-tip">
                <el-alert
                    title="您还没有已确认的预约"
                    type="warning"
                    description="请先预约老师并等待教师确认后，才能创建课程安排。"
                    show-icon
                    :closable="false"
                />
                <div class="mt-3 text-center">
                    <el-button type="primary" @click="goToTutoringList">去预约老师</el-button>
                </div>
            </div>
            <el-form v-else :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="100px">
                <el-form-item label="选择老师" prop="teacherId">
                    <el-select v-model="scheduleForm.teacherId" placeholder="请选择老师" @change="handleTeacherChange">
                        <el-option
                            v-for="teacher in availableTeachers"
                            :key="teacher.id"
                            :label="teacher.name"
                            :value="teacher.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="课程" prop="tutoringId">
                    <el-select v-model="scheduleForm.tutoringId" placeholder="请选择课程" :disabled="!scheduleForm.teacherId">
                        <el-option
                            v-for="item in filteredTutorings"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                        v-model="scheduleForm.startTime"
                        type="datetime"
                        placeholder="选择开始时间"
                    />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="scheduleForm.endTime"
                        type="datetime"
                        placeholder="选择结束时间"
                    />
                </el-form-item>
                <el-form-item label="上课地点" prop="location">
                    <el-input v-model="scheduleForm.location" placeholder="请输入上课地点" />
                </el-form-item>
                <el-form-item label="具体要求" prop="requirements">
                    <el-input
                        v-model="scheduleForm.requirements"
                        type="textarea"
                        placeholder="请输入具体要求"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="createDialogVisible = false">取消</el-button>
                    <el-button v-if="availableTeachers.length > 0" type="primary" @click="submitSchedule">提交</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 提交反馈对话框 -->
        <el-dialog v-model="feedbackDialogVisible" title="提交课程反馈" width="500px">
            <el-form :model="feedbackForm" :rules="feedbackRules" ref="feedbackFormRef" label-width="100px">
                <el-form-item label="评分" prop="rating">
                    <el-rate v-model="feedbackForm.rating" />
                </el-form-item>
                <el-form-item label="反馈内容" prop="feedback">
                    <el-input
                        v-model="feedbackForm.feedback"
                        type="textarea"
                        placeholder="请输入课程反馈"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="feedbackDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitFeedback">提交</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="课程详情" width="600px">
            <div v-if="currentSchedule" class="schedule-detail">
                <div class="detail-item">
                    <span class="label">课程名称：</span>
                    <span>{{ currentSchedule.tutoringTitle }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">教师姓名：</span>
                    <span>{{ currentSchedule.teacherName }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课时间：</span>
                    <span>{{ formatDateTime(currentSchedule.startTime) }} - {{ formatDateTime(currentSchedule.endTime) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课地点：</span>
                    <span>{{ currentSchedule.location }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">具体要求：</span>
                    <span>{{ currentSchedule.requirements }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">状态：</span>
                    <el-tag :type="getStatusType(currentSchedule.status)">
                        {{ getStatusText(currentSchedule.status) }}
                    </el-tag>
                </div>
                <div class="detail-item">
                    <span class="label">支付状态：</span>
                    <el-tag :type="currentSchedule.isPaid ? 'success' : 'warning'">
                        {{ currentSchedule.isPaid ? '已支付' : '未支付' }}
                    </el-tag>
                </div>
                <div v-if="currentSchedule.feedback" class="detail-item">
                    <span class="label">课程反馈：</span>
                    <span>{{ currentSchedule.feedback }}</span>
                </div>
                <div v-if="currentSchedule.rating" class="detail-item">
                    <span class="label">评分：</span>
                    <el-rate v-model="currentSchedule.rating" disabled />
                </div>
                
                <!-- 添加支付按钮 -->
                <div class="detail-actions" v-if="(currentSchedule.status === 1 || currentSchedule.status === 2) && !currentSchedule.isPaid">
                    <el-button type="warning" @click="goToPayment(currentSchedule)">前往支付</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 待确认课程详情对话框 -->
        <el-dialog v-model="pendingDetailDialogVisible" title="课程详情" width="600px">
            <div v-if="currentPendingSchedule" class="schedule-detail">
                <div class="detail-item">
                    <span class="label">课程名称：</span>
                    <span>{{ currentPendingSchedule.tutoringTitle }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">教师姓名：</span>
                    <span>{{ currentPendingSchedule.teacherName }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课时间：</span>
                    <span>{{ formatDateTime(currentPendingSchedule.startTime) }} - {{ formatDateTime(currentPendingSchedule.endTime) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">上课地点：</span>
                    <span>{{ currentPendingSchedule.location }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">具体要求：</span>
                    <span>{{ currentPendingSchedule.requirements }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">状态：</span>
                    <el-tag :type="getStatusType(currentPendingSchedule.status)">
                        {{ getStatusText(currentPendingSchedule.status) }}
                    </el-tag>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tutoringService } from '@/api/tutoring'
import { formatDateTime } from '@/utils/format'
import { useRouter } from 'vue-router'

const schedules = ref([])
const pendingSchedules = ref([])
const availableTutorings = ref([])
const availableTeachers = ref([])
const filteredTutorings = ref([])
const createDialogVisible = ref(false)
const feedbackDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const pendingDetailDialogVisible = ref(false)
const currentSchedule = ref(null)
const currentPendingSchedule = ref(null)
const scheduleFormRef = ref(null)
const feedbackFormRef = ref(null)
const router = useRouter()
const activeTab = ref('confirmed')
const pendingLoading = ref(false)

const scheduleForm = ref({
    teacherId: '',
    tutoringId: '',
    startTime: '',
    endTime: '',
    location: '',
    requirements: ''
})

const feedbackForm = ref({
    rating: 5,
    feedback: ''
})

const scheduleRules = {
    teacherId: [{ required: true, message: '请选择老师', trigger: 'change' }],
    tutoringId: [{ required: true, message: '请选择课程', trigger: 'change' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    location: [{ required: true, message: '请输入上课地点', trigger: 'blur' }]
}

const feedbackRules = {
    rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
    feedback: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }]
}

// 获取学生的时间安排列表
const getStudentSchedules = async () => {
    try {
        const response = await tutoringService.getStudentSchedules()
        
        // 获取课程安排数据
        const schedulesData = response.data || []
        
        // 检查每个课程的支付状态
        for (let i = 0; i < schedulesData.length; i++) {
            const schedule = schedulesData[i]
            try {
                // 查询课程的支付状态
                const paymentResponse = await tutoringService.checkSchedulePaymentStatus(schedule.id)
                // 将支付状态添加到课程数据中
                schedule.isPaid = paymentResponse.data.isPaid
                console.log(`课程ID ${schedule.id} 支付状态: ${schedule.isPaid ? '已支付' : '未支付'}`)
            } catch (error) {
                console.error(`获取课程 ${schedule.id} 支付状态失败:`, error)
                schedule.isPaid = false // 默认为未支付
            }
        }
        
        schedules.value = schedulesData
    } catch (error) {
        console.error('获取课程安排失败:', error)
        ElMessage.error('获取课程安排失败')
    }
}

// 获取可用的家教信息
const getAvailableTutorings = async () => {
    try {
        // 改为获取学生已确认预约的老师的课程
        const response = await tutoringService.getStudentConfirmedTutorings()
        console.log('获取到的课程数据:', response.data)
        
        availableTutorings.value = response.data || []
        
        // 提取不重复的老师信息
        const teacherMap = new Map()
        availableTutorings.value.forEach(tutoring => {
            if (!teacherMap.has(tutoring.teacherId)) {
                teacherMap.set(tutoring.teacherId, {
                    id: tutoring.teacherId,
                    name: tutoring.teacherName || `教师${tutoring.teacherId}`
                })
            }
        })
        
        availableTeachers.value = Array.from(teacherMap.values())
        console.log('提取的老师信息:', availableTeachers.value)
        
        // 如果没有数据，显示提示信息
        if (availableTeachers.value.length === 0) {
            ElMessage({
                message: '您还没有已确认的预约，请先预约老师并等待确认后再创建课程安排',
                type: 'warning',
                duration: 5000,
                showClose: true
            })
        }
    } catch (error) {
        console.error('获取课程数据失败:', error)
        ElMessage({
            message: error.response?.data?.message || '获取可用课程失败，请确保您有已确认的预约',
            type: 'error',
            duration: 5000,
            showClose: true
        })
    }
}

// 处理老师选择变化
const handleTeacherChange = (teacherId) => {
    scheduleForm.value.tutoringId = '' // 清空已选课程
    
    if (teacherId) {
        // 根据选择的老师筛选课程
        filteredTutorings.value = availableTutorings.value.filter(
            tutoring => tutoring.teacherId === teacherId
        )
    } else {
        filteredTutorings.value = []
    }
}

// 获取状态类型
const getStatusType = (status) => {
    const types = {
        0: 'warning',  // 待确认
        1: 'success',  // 已确认
        2: 'info',     // 已完成
        3: 'danger'    // 已取消
    }
    return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const texts = {
        0: '待确认',
        1: '已确认',
        2: '已完成',
        3: '已取消'
    }
    return texts[status] || '未知'
}

// 显示创建对话框
const showCreateDialog = () => {
    scheduleForm.value = {
        teacherId: '',
        tutoringId: '',
        startTime: '',
        endTime: '',
        location: '',
        requirements: ''
    }
    filteredTutorings.value = []
    createDialogVisible.value = true
}

// 提交课程安排
const submitSchedule = async () => {
    if (!scheduleFormRef.value) return
    
    await scheduleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await tutoringService.createSchedule(scheduleForm.value)
                ElMessage.success('课程安排创建成功，等待教师确认')
                createDialogVisible.value = false
                getStudentSchedules()
            } catch (error) {
                // 显示更详细的错误信息
                const errorMsg = error.response?.data?.message || 
                                (error.response?.data?.data || '创建失败');
                ElMessage({
                    message: errorMsg,
                    type: 'error',
                    duration: 5000,
                    showClose: true
                });
            }
        }
    })
}

// 显示反馈对话框
const showFeedbackDialog = (schedule) => {
    currentSchedule.value = schedule
    feedbackForm.value = {
        rating: 5,
        feedback: ''
    }
    feedbackDialogVisible.value = true
}

// 提交反馈
const submitFeedback = async () => {
    if (!feedbackFormRef.value) return
    
    await feedbackFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                await tutoringService.submitFeedback(
                    currentSchedule.value.id,
                    feedbackForm.value.feedback,
                    feedbackForm.value.rating
                )
                ElMessage.success('反馈提交成功')
                feedbackDialogVisible.value = false
                getStudentSchedules()
            } catch (error) {
                ElMessage.error(error.response?.data?.message || '提交失败')
            }
        }
    })
}

// 显示详情
const showDetail = async (schedule) => {
    try {
        const response = await tutoringService.getScheduleDetail(schedule.id)
        currentSchedule.value = response.data
        
        // 添加支付状态信息
        if (schedule.isPaid !== undefined) {
            currentSchedule.value.isPaid = schedule.isPaid
        } else {
            try {
                // 如果没有支付状态信息，单独查询
                const paymentResponse = await tutoringService.checkSchedulePaymentStatus(schedule.id)
                currentSchedule.value.isPaid = paymentResponse.data.isPaid
            } catch (err) {
                console.error('获取支付状态失败:', err)
                currentSchedule.value.isPaid = false // 默认未支付
            }
        }
        
        detailDialogVisible.value = true
    } catch (error) {
        ElMessage.error('获取详情失败')
    }
}

// 跳转到家教列表页面
const goToTutoringList = () => {
    createDialogVisible.value = false
    router.push('/tutoring/list')
}

// 跳转到支付页面
const goToPayment = (schedule) => {
    // 直接使用课程安排ID，不再需要bookingId
    localStorage.setItem('paymentScheduleId', schedule.id)
    router.push('/payment/create')
}

// 获取学生的待确认课程安排
const getPendingSchedules = async () => {
    pendingLoading.value = true
    try {
        const response = await tutoringService.getStudentPendingSchedules()
        console.log('获取到的待确认课程安排数据:', response.data)
        
        // 打印每个课程的createdBy字段
        if (response.data && response.data.length > 0) {
            console.log('课程创建者信息:')
            response.data.forEach((item, index) => {
                console.log(`课程${index + 1} - ID: ${item.id}, 创建者: ${item.createdBy}, 教师ID: ${item.teacherId}, 学生ID: ${item.studentId}`)
            })
        }
        
        pendingSchedules.value = response.data || []
        
        // 确保日期时间字段是Date对象
        if (pendingSchedules.value && pendingSchedules.value.length > 0) {
            pendingSchedules.value = pendingSchedules.value.map(schedule => {
                if (schedule.startTime && typeof schedule.startTime === 'string') {
                    schedule.startTime = new Date(schedule.startTime)
                }
                if (schedule.endTime && typeof schedule.endTime === 'string') {
                    schedule.endTime = new Date(schedule.endTime)
                }
                // 确保createdBy字段存在，如果不存在则设置默认值
                if (!schedule.createdBy) {
                    console.log(`课程ID ${schedule.id} 没有createdBy字段，设置默认值为STUDENT`)
                    schedule.createdBy = 'STUDENT' // 默认为学生创建
                }
                return schedule
            })
        }
    } catch (error) {
        console.error('获取待确认课程安排失败:', error)
        ElMessage.error('获取待确认课程安排失败: ' + (error.message || '未知错误'))
    } finally {
        pendingLoading.value = false
    }
}

// 处理标签页切换
const handleTabClick = (tab) => {
    if (tab.props.name === 'pending') {
        getPendingSchedules()
    } else {
        getStudentSchedules()
    }
}

// 确认课程安排
const handleConfirm = async (schedule) => {
    // 学生只能确认教师创建的课程
    if (schedule.createdBy !== 'TEACHER') {
        ElMessage.error('您不能确认自己创建的课程安排，只有教师可以确认')
        return
    }
    
    try {
        await ElMessageBox.confirm('确认接受该课程安排？', '提示', {
            type: 'warning'
        })
        await tutoringService.updateStudentScheduleStatus(schedule.id, 1)
        ElMessage.success('已确认课程安排')
        getPendingSchedules()
        getStudentSchedules() // 刷新已确认课程列表
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('确认失败')
        }
    }
}

// 取消课程安排
const handleCancel = async (schedule) => {
    try {
        await ElMessageBox.confirm('确认取消该课程安排？', '提示', {
            type: 'warning'
        })
        await tutoringService.updateStudentScheduleStatus(schedule.id, 3)
        ElMessage.success('已取消课程安排')
        getPendingSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('取消失败')
        }
    }
}

// 显示待确认课程详情
const showPendingDetail = (schedule) => {
    console.log('显示详情的待确认课程安排:', schedule)
    // 确保日期时间字段是Date对象
    const detailSchedule = { ...schedule }
    if (detailSchedule.startTime && typeof detailSchedule.startTime === 'string') {
        detailSchedule.startTime = new Date(detailSchedule.startTime)
    }
    if (detailSchedule.endTime && typeof detailSchedule.endTime === 'string') {
        detailSchedule.endTime = new Date(detailSchedule.endTime)
    }
    currentPendingSchedule.value = detailSchedule
    pendingDetailDialogVisible.value = true
}

// 删除课程安排
const deleteSchedule = async (id) => {
    try {
        // 找到当前课程的状态
        const schedule = schedules.value.find(s => s.id === id);
        const statusText = schedule ? (schedule.status === 3 ? '已取消' : '已完成') : '';
        
        await ElMessageBox.confirm(`确定要删除这个${statusText}的课程安排吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await tutoringService.deleteSchedule(id)
        ElMessage.success('删除成功')
        getStudentSchedules()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message || '未知错误'))
        }
    }
}

onMounted(() => {
    getStudentSchedules()
    getAvailableTutorings()
})
</script>

<style scoped>
.student-schedule {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.schedule-detail {
    padding: 20px;
}

.detail-item {
    margin-bottom: 15px;
    line-height: 1.5;
}

.detail-item .label {
    font-weight: bold;
    margin-right: 10px;
    color: #666;
}

.empty-data-tip {
    padding: 20px 0;
}

.mt-3 {
    margin-top: 15px;
}

.text-center {
    text-align: center;
}

.loading-container {
    padding: 20px;
}

.detail-actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 10px;
}
</style> 